package com.augurit.gzcgwsp.sendNotice.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.syslog.tool.SysTraceLogWriter;
import com.augurit.common.util.PageUtils;
import com.augurit.gzcgwsp.hwgz.web.form.YwHwShSqbForm;
import com.augurit.gzcgwsp.sendNotice.convert.YwWebserviceInfoConvert;
import com.augurit.gzcgwsp.sendNotice.dao.YwWebserviceInfoDao;
import com.augurit.gzcgwsp.sendNotice.entity.YwWebserviceInfo;
import com.augurit.gzcgwsp.sendNotice.service.IAcceptNoticeService;
import com.augurit.gzcgwsp.sendNotice.service.ICreateNoticeCommonPartService;
import com.augurit.gzcgwsp.sendNotice.service.IYwWebserviceInfoService;
import com.augurit.gzcgwsp.sendNotice.web.form.YwWebserviceInfoForm;
import com.augurit.gzcgwsp.webservice.SFTPUtil;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.common.service.impl.WfBusClientServiceImpl;

@Service
@Transactional
public class YwWebserviceInfoServiceImpl extends WfBusClientServiceImpl<YwWebserviceInfoForm>  implements IYwWebserviceInfoService {
	Logger logger = (Logger) LoggerFactory.getLogger(YwWebserviceInfoServiceImpl.class);
	@Autowired
	private YwWebserviceInfoDao ywWebserviceInfoDao;

	@Autowired
	private ICreateNoticeCommonPartService createNoticeCommonPartService;
	
	@Autowired
	private IAcceptNoticeService acceptNoticeService;

	/**
	 * 保存webservice接口的信息
	 * 
	 * @param ywWebserviceInfo
	 */
	public void save(YwWebserviceInfo ywWebserviceInfo) {
		if(StringUtils.isBlank(ywWebserviceInfo.getCallTimes())){
			ywWebserviceInfo.setCallTimes("0");
		}		
		ywWebserviceInfoDao.save(ywWebserviceInfo);
	}
	
	public YwWebserviceInfo getYwWebserviceInfoById(Long id) {
		YwWebserviceInfo ywWebserviceInfo = ywWebserviceInfoDao.get(id);
		return ywWebserviceInfo;
	}

	/**
	 * 产生一个YwWebserviceInfo实体
	 * 
	 * @param noticeLabelMap 通知的键值
	 * @param flag 判断是否是我们系统收的案，而且是窗口收案环节，是则为true
	 * @param acceptNo 受理号          
	 * @param approvalNo 方欣那边的受理号
	 * @return YwWebserviceInfo实体
	 */
	public YwWebserviceInfo createYwWebserviceInfo(
			Map<String, String> noticeLabelMap,boolean flag,String acceptNo,String approvalNo) {
		
		Locale locale = Locale.getDefault(); 
		ResourceBundle localResource = ResourceBundle.getBundle("interfaceExchange", locale); 
		
		String wsdl = localResource.getString("fxwsdl");
//		String wsdl = "http://192.168.15.243:9090/iexchange/services/SPXT_ApprovalInfoFeedBack_Service?wsdl";	
		YwWebserviceInfo ywWebserviceInfo = new YwWebserviceInfo();
		String para = createNoticeCommonPartService
				.createNotice(noticeLabelMap);
		String paraTwo = localResource.getString("SPXT_ApprovalInfoFeedBack_Service");
		String paraThree = localResource.getString("feedBackApprovalInfo");
		ywWebserviceInfo.setParaTwo(paraTwo);
		ywWebserviceInfo.setParaThree(paraThree);
		ywWebserviceInfo.setWsdlPara(wsdl);
		ywWebserviceInfo.setProduceDate(new Date());
		ywWebserviceInfo.setAcceptNo(acceptNo);
		ywWebserviceInfo.setParaFour(approvalNo);
		System.out.println("|||||||||||||||||||||||||||| = "+approvalNo);
		if(flag == true){//如果是我们系统收的案，而且是窗口收案环节，则为true
			ywWebserviceInfo.setIsSended("2");//设置为2，定时不会调用到，等方欣那边反馈Approvalno后，把它设置为空，才调用
		}
		ywWebserviceInfo.setXmlStr(para);
//		// 文件路径
//		String path = localResource.getString("path");
//		String formatDate = new SimpleDateFormat("yyyyMMddHHmmss")
//				.format(new Date());
//		int random = new Random().nextInt(1000000);
//		String targetFilePath = path + formatDate + random + ".txt";
//		System.out.println("targetFilePath------------------"+targetFilePath);
//		ywWebserviceInfo.setFilePath(targetFilePath);
//		try {
//			File f = new File(targetFilePath);
//			if (!f.exists()) {
//				f.createNewFile();
//			}
////			BufferedWriter output = new BufferedWriter(new FileWriter(f));
////			output.write(para);
////			output.close();			
//			OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream(f), "gbk");    // 设置编码
//			outputStream.write(para);
//			outputStream.close();
//			//上传到另外一台机器
////			SFTPUtil.uploadOtherFileForFx(targetFilePath, targetFilePath);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			logger.error("(接口)产生一个YwWebserviceInfo实体异常"+SysTraceLogWriter.MESSAGE_SEPARATOR + e.getMessage(), e);
//			e.printStackTrace();
//		}// 不存在则创建
		return ywWebserviceInfo;
	}
	
	
	/**
	 * 获得还没有发送的记录
	 * @return
	 */
	public List getNoticeYwWebserviceInfo(){
		return ywWebserviceInfoDao.getNoticeYwWebserviceInfo();
	}
	
	/**
	 * 获得还没有发送的记录  公示结束接口
	 * @return
	 */
	public List getStopPublicYwWebserviceInfo(){
		return ywWebserviceInfoDao.getStopPublicYwWebserviceInfo();
	}
	
	/**
	 * 当webservice调用成功，则把改记录的isSended字段的值改成1
	 * @param id
	 */
	public void changState(long id){
		ywWebserviceInfoDao.changState(id);
	}
	
	/**
	 * 根据acceptNo获取结束公示的一条记录
	 * @param acceptNo
	 * @return
	 */
	public YwWebserviceInfo getStopYwWebserviceInfoByAcceptNo(String acceptNo){
		return ywWebserviceInfoDao.getStopYwWebserviceInfoByAcceptNo(acceptNo);
	}
	
	/**
	 * 获得还没有发送的同步用户或者行政组织记录
	 * @return
	 */
	public List getsyncUserAndOrgYwWebServiceInfo(){
		return ywWebserviceInfoDao.getsyncUserAndOrgYwWebServiceInfo();
	}
	
	/**
	 * 把改记录的isSended字段的值改成空，则定时器可以查到
	 * @param acceptNo 系统受理号
	 * @param approvalNo 方欣那边的受理号
	 */
	public void changStateToNullByAcceptNo(String acceptNo,String approvalNo){
		ywWebserviceInfoDao.changStateToNullByAcceptNo(acceptNo,approvalNo);
	}
	
	/**
	 * 保存数据到YwWebserviceInfo表，用于交换给方欣
	 * @param sqrq								申请日期
	 * @param acceptNo							受理号
	 * @param cbyw								承办业务
	 * @param lxr								联系人
	 * @param sjr								收件人
	 * @param sqdw								申请单位
	 * @param businessCode						业务编码
	 * @param approvalNo						长预受理号
	 * @param loginUserName						登录用户名称
	 * @param dpm								部门
	 * @param thisNoteActivityName				本节点的英文名称
	 * @param acceptTime						办理时间
	 * @param flag								是否是窗口收案环节
	 * @param thisNoteActivityChineseName		本节点的中午名称
	 * @param instance							
	 */
	public void saveYwWebserviceInfo(Date sqrq,String acceptNo,String cbyw,String lxr,String sjr,String sqdw,String businessCode,String approvalNo,
			String loginUserName,String dpm,String thisNoteActivityName,Date acceptTime,boolean flag,String thisNoteActivityChineseName,
			WfBusInstanceTaskForm instance){
		//生成收件通知书map
		Map<String,String> noticeMap = acceptNoticeService.getCommonAcceptNoticeMap(sqrq, acceptNo, cbyw, lxr, sjr, sqdw, instance);
		//生成收件通知书
		String notice = acceptNoticeService.createAcceptNotice(noticeMap);							
		//生成标签与值对应map 
		Map<String,String> noticeLabelMap = createNoticeCommonPartService.getCommonNoticeLabel(approvalNo, acceptNo, businessCode,
				sqdw, cbyw, instance, loginUserName, dpm, thisNoteActivityName, thisNoteActivityChineseName, notice, acceptTime);
		//生成ywWebserviceInfo
		YwWebserviceInfo ywWebserviceInfo = this.createYwWebserviceInfo(noticeLabelMap,flag,acceptNo,approvalNo);
		this.save(ywWebserviceInfo);	
	}
	
	/**
	 * 记录调用次数，一天发送50次失败的都没有成功的话，第二天再交换
	 * @param id
	 */
	public void callRecord(Long id){
		YwWebserviceInfo ywWebserviceInfo = this.getYwWebserviceInfoById(id);
		String callTimes = ywWebserviceInfo.getCallTimes();//调用次数
		Date callDate = ywWebserviceInfo.getCallDate();//调用日期
		if(StringUtils.isNotBlank(callTimes)){
			int callTime = 0;
//			System.out.println("-----------------------------------------------"+Integer.parseInt(callTimes));
			if(Integer.parseInt(callTimes) == 50){
				callTime = 1;
			}else{
				callTime = Integer.parseInt(callTimes) + 1;
			}
			ywWebserviceInfo.setCallTimes(String.valueOf(callTime));
		}else{
			ywWebserviceInfo.setCallTimes("1");
		}
		ywWebserviceInfo.setCallDate(new Date());
		this.save(ywWebserviceInfo);
	}
	
	public Page<YwWebserviceInfoForm> searchPage(Page<YwWebserviceInfoForm> page,Map map) {
		StringBuffer sb = new StringBuffer();
		sb.append(" from YwWebserviceInfo wb where 1=1 ");
		String acceptNo = (String)map.get("acceptNo");
		String isSended = (String)map.get("isSended");
		String produceDate = (String)map.get("produceDate");
		if(StringUtils.isNotBlank(acceptNo)){
			sb.append(" and wb.acceptNo like '%"+acceptNo+"%'");
		}
		if(StringUtils.isNotBlank(isSended)){
			if("发送失败".equals(isSended)){//失败
				sb.append(" and wb.isSended is null");
			}else if("其他".equals(isSended)){//其他
				sb.append(" and wb.isSended is not null and wb.isSended not in ('1','2')");
			}else{//发送成功  或者  等待反馈长受理号
				sb.append(" and wb.isSended='"+isSended+"'");
			}			
		}
		if(StringUtils.isNotBlank(produceDate)){
			sb.append(" and to_char(wb.produceDate,'yyyy-MM-dd') = '"+produceDate.substring(0, 10)+"'");
		}
		sb.append(" order by id desc");
		Map paraMap=new HashMap();
		Page pg = PageUtils.newPageInstance(page);
		this.ywWebserviceInfoDao.findPage(pg, sb.toString(),paraMap);
		// 建立新的分页对象
		List<YwWebserviceInfoForm> list = YwWebserviceInfoConvert.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	public YwWebserviceInfoForm get(Long id) {
		YwWebserviceInfo entity = ywWebserviceInfoDao.get(id);
		YwWebserviceInfoForm form=YwWebserviceInfoConvert.convertVoToForm(entity);
		return form;
	}

	@Override
	public Page<YwWebserviceInfoForm> search(Page<YwWebserviceInfoForm> page,
			List<PropertyFilter> filters) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Page<YwWebserviceInfoForm> search(Page<YwWebserviceInfoForm> page,
			YwWebserviceInfoForm form) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void delete(Long... ids) {
		ywWebserviceInfoDao.delete(ids);
	}

	@Override
	public void save(YwWebserviceInfoForm... forms) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void save(YwWebserviceInfoForm forms) {
		// TODO Auto-generated method stub
		
	}
}
